﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace PADWH35
{

    public partial class SafetyProductionBoard : Form
    {

        // <summary>
        /// 窗体改变前的Width宽度
        /// </summary>
        private int iForm_ResizeBefore_Width;

        /// <summary>
        /// 窗体改变前的Height高度
        /// </summary>
        private int iForm_ResizeBefore_Height;

        /// <summary>
        /// 取得Form中控件中初始的字体大小，即无论Form多大此字体都是Form中最小值
        /// </summary>
        private Dictionary<Control, float> FontSizeMin = new Dictionary<Control, float>();

        /// <summary>
        /// 宽比例，float类型，此处为每次改后窗体的宽度 除以改变前窗体的宽度的比例
        /// </summary>
        private float fRatio_Width;

        /// <summary>
        /// 高比例，float类型，此处为每次改后窗体的高度 除以改变前窗体的高度的比例
        /// </summary>
        private float fRatio_Height;


        public SafetyProductionBoard()
        {
            InitializeComponent();

            //设置最小大小为窗体打开的初始大小
            this.MinimumSize = this.Size;

            FontSizeMin = new Dictionary<Control, float>();
            //取得Form中控件中初始的字体大小 //若此From中字体不统一，则此处为数组。
            getlist(this);
            //FontSizeMin = this.label1.Font.Size;
            //获得窗体改变前的Form的宽度与高度 //赋初始值
            iForm_ResizeBefore_Width = this.Size.Width;
            iForm_ResizeBefore_Height = this.Size.Height;
        }

        /// <summary>
        /// 获取控件字体大小值
        /// </summary>
        /// <param name="controls"></param>
        private void getlist(Control controls)
        {
            foreach (Control OneCon in controls.Controls)
            {
                FontSizeMin.Add(OneCon, OneCon.Font.Size);
                if (OneCon.Controls.Count > 0)
                {
                    getlist(OneCon);// 如Form内还有控件中的控件，此处则可递归改变大小，此处为重点中的重点 

                }
            }
        }

        private void SafetyProductionBoard_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            //this.label36.Text = Environment.UserDomainName + "\\" + Environment.UserName;
            Refreshdata();
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        public void Refreshdata()
        {
            DateTime now = DateTime.Now;
            string year = now.ToString("yyyy");
            string mon = now.ToString("MM");
            string day = now.ToString("dd");
            label29.Text = year;
            label30.Text = mon;
            label31.Text = day;
            string city = string.Empty;
            string dept = string.Empty;
            string userid = Environment.UserName;
            DateTime startTime = new DateTime();
            string sql = $"select * from dbo.BoardInfo where id=N'{userid}'";
            var result = ExecuteDt(sql);
            if (result.Rows.Count > 0)
            {
                city = result.Rows[0]["nvarchar03"].ToString();
                dept = result.Rows[0]["nvarchar02"].ToString();
                startTime = Convert.ToDateTime(result.Rows[0]["nvarchar01"].ToString());
            }
            try
            {
                string temperature;
                string weather = string.Empty;
                //bool ifcomfromweb = Convert.ToBoolean(GetConfig("ifcomfromweb"));

                label3.Text = $"利宾来塑胶工业（{city}）有限公司";
                //var weather = getweather(city);
                string url = string.Empty;
                //获取天气数据(数据来源自高德地图参考：https://lbs.amap.com/api/webservice/guide/api/weatherinfo)
                if (city == "深圳")
                {
                    url = "https://restapi.amap.com/v3/weather/weatherInfo?key=51d147a603cd4a24c427e722b49bd0a6&city=440309&extensions=base&output=JSON";
                }
                else if (city == "昆山")
                {
                    url = "https://restapi.amap.com/v3/weather/weatherInfo?key=51d147a603cd4a24c427e722b49bd0a6&city=320583&extensions=base&output=JSON";
                }
                string getJson = Get(url);
                //josn反序列化
                Root rt = JsonConvert.DeserializeObject<Root>(getJson);
                temperature = rt.lives[0].temperature;
                weather = rt.lives[0].weather;
                //MessageBox.Show(getJson);
                //string nowWeather = weather[10];
                //temperature = MidStrEx(nowWeather, "气温：", "℃");

                //temperature = GetConfig("temperature");

                //label36.Text = temperature;
                label53.Text = weather + "  " + temperature + "℃";
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
                MessageBox.Show("温度初始化失败，请修改配置文件！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            try
            {
                string syear = startTime.ToString("yyyy");
                string smon = startTime.ToString("MM");
                string sday = startTime.ToString("dd");
                label26.Text = syear;
                label27.Text = smon;
                label28.Text = sday;
                label52.Text = dept;
                label37.Text = DateDiff(startTime, now).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据初始化失败，请修改配置文件！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 计算天数
        /// </summary>
        /// <param name="dateStart"></param>
        /// <param name="dateEnd"></param>
        /// <returns></returns>
        private int DateDiff(DateTime dateStart, DateTime dateEnd)
        {
            DateTime start = Convert.ToDateTime(dateStart.ToShortDateString());
            DateTime end = Convert.ToDateTime(dateEnd.ToShortDateString());
            TimeSpan sp = end.Subtract(start);
            return sp.Days;
        }

        /// <summary>
        /// 截取两字符间的字符
        /// </summary>
        /// <param name="sourse"></param>
        /// <param name="startstr"></param>
        /// <param name="endstr"></param>
        /// <returns></returns>
        public static string MidStrEx(string sourse, string startstr, string endstr)
        {
            string result = string.Empty;
            int startindex, endindex;
            try
            {
                startindex = sourse.IndexOf(startstr);
                if (startindex == -1)
                    return result;
                string tmpstr = sourse.Substring(startindex + startstr.Length);
                endindex = tmpstr.IndexOf(endstr);
                if (endindex == -1)
                    return result;
                result = tmpstr.Remove(endindex);
            }
            catch (Exception ex)
            {
                WriteLog.Writelog("MidStrEx Err:" + ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 获取城市天气
        /// </summary>
        /// <param name="city"></param>
        /// <returns></returns>
        //public string[] getweather(string city)
        //{
        //    try
        //    {
        //        cn.com.webxml.www.WeatherWebService w = new cn.com.webxml.www.WeatherWebService();
        //        string[] weatherInfo = w.getWeatherbyCityName(city);
        //        return weatherInfo;
        //    }
        //    catch (Exception ex)
        //    {
        //        WriteLog.Writelog(ex.ToString());

        //        return null;
        //    }
        //}

        private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void label10_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 时间刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            string hour = now.ToString("HH");
            string min = now.ToString("mm");
            string sec = now.ToString("ss");
            label47.Text = hour;
            label48.Text = min;
            label49.Text = sec;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 获取配置文件
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetConfig(string name)
        {
            string value = null;
            XmlDocument doc = new XmlDocument();
            //获得配置文件的全路径  
            string strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;//AppDomain.CurrentDomain.BaseDirectory.ToString() + ".exe.config";
            doc.Load(strFileName);
            //找出名称为“add”的所有元素  
            XmlNodeList nodes = doc.GetElementsByTagName("add");
            for (int i = 0; i < nodes.Count; i++)
            {
                //获得将当前元素的key属性  
                XmlAttribute att = nodes[i].Attributes["name"];
                //根据元素的第一个属性来判断当前的元素是不是目标元素  
                if (att.Value == name)
                {
                    //对目标元素中的第二个属性赋值  
                    att = nodes[i].Attributes["connectionString"];
                    value = att.Value;
                    break;
                }
            }
            //保存上面的修改  
            return value;
        }

        //private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    Form s = new SetSafetyProductionBoard();
        //    s.ShowDialog();
        //    Refreshdata();
        //}

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            Refreshdata();
        }

        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string Get(string Url)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            ServicePointManager.ServerCertificateValidationCallback = new
             RemoteCertificateValidationCallback
              (
               delegate { return true; }
               );
            //System.GC.Collect();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            return retString;
        }

        private void SafetyProductionBoard_SizeChanged(object sender, EventArgs e)
        {
            //AutoSizeFormClass asc = new AutoSizeFormClass();
            //asc.ControlAutoSize(this);
        }

        private void SafetyProductionBoard_ResizeEnd(object sender, EventArgs e)
        {
            //窗体改变后Form的宽度与高度及宽比例和高比例

            fRatio_Width = (this.Size.Width / (float)iForm_ResizeBefore_Width);
            fRatio_Height = (this.Size.Height / (float)iForm_ResizeBefore_Height);
            AutoResize(this);
            ////获得下一次窗体改变前的Form的宽度与高度

            iForm_ResizeBefore_Width = this.Size.Width;
            iForm_ResizeBefore_Height = this.Size.Height;
        }

        // <summary>
        /// 自适应窗体大小的方法，递归
        /// </summary>
        /// <param name="theControl"></param>
        private void AutoResize(Control theControl)  //核心代码
        {
            #region 控制控件自适应UI大小
            foreach (Control OneCon in theControl.Controls)   //根据原大小等比例放大
            {
                OneCon.Left = Convert.ToInt32((OneCon.Left * fRatio_Width));
                OneCon.Top = Convert.ToInt32((OneCon.Top * fRatio_Height));
                OneCon.Width = Convert.ToInt32(OneCon.Width * fRatio_Width);
                OneCon.Height = Convert.ToInt32(OneCon.Height * fRatio_Height);
                if (OneCon.Controls.Count > 0)
                {
                    AutoResize(OneCon);//如Form内还有控件中的控件，此处则可递归改变大小，此处为重点中的重点  
                }
                #region 自动更改字体的大小  //2020-03-23 19:21:50 更新
                // 当前控件（OneCon.Font.Size） 乘以(8)  长宽比例中最小值 (Math.Min(fRatio_Width, fRatio_Height)
                //Math.Round(数值, 2) //保留两位有效数字
                float currentSize = float.Parse(Math.Round(OneCon.Font.Size * (Math.Min(fRatio_Width, fRatio_Height)), 2).ToString());
                if (currentSize > FontSizeMin[OneCon])
                    OneCon.Font = new Font(OneCon.Font.Name, currentSize, OneCon.Font.Style, OneCon.Font.Unit);
                else
                    OneCon.Font = new Font(OneCon.Font.Name, FontSizeMin[OneCon], OneCon.Font.Style, OneCon.Font.Unit);
                //某种程度上来说 if 语句都可以改成三目运算符， 举例： m=a>b?a:b; 表示先判断a是否大于b，若a>b,则将a的值赋给m，若不符合a>b,则将b的值赋给m
                //float NowSize = currentSize > FontSizeMin ? currentSize : FontSizeMin;
                //OneCon.Font = new Font(OneCon.Font.Name, NowSize, OneCon.Font.Style, OneCon.Font.Unit);
                #endregion
            }
            #endregion
        }

        private void SafetyProductionBoard_ResizeEnd_1(object sender, EventArgs e)
        {

        }
        private static string conStr = "Data Source=192.168.100.250;Initial Catalog=EpicorRelationData;User ID=szmis;pwd=szmis";
        public static int ExecuteSql(String Sqlstr, SqlParameter[] param = null, int Timeout = 30)
        {
            using (SqlConnection conn = new SqlConnection(conStr))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandTimeout = Timeout;
                cmd.Connection = conn;
                cmd.CommandText = Sqlstr;
                if (param != null) cmd.Parameters.AddRange(param);
                conn.Open();
                int i = cmd.ExecuteNonQuery();
                conn.Close();
                return i;
            }
        }

        public static DataTable ExecuteDt(String Sqlstr, SqlParameter[] param = null, int Timeout = 30)
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(conStr))
                {

                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandTimeout = Timeout;
                    cmd.CommandText = Sqlstr;
                    if (param != null) cmd.Parameters.AddRange(param);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    conn.Open();
                    da.Fill(dt);
                    conn.Close();
                    return dt;
                }
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
                return null;
            }
        }
    }
}
